const $wx = require('weixin-js-sdk')
import { wxTicketConfig } from '@/api/common.js'
import { isWeiXin, isIOS } from '@/utils/util.js'

const defaultShareTitle = '蒙古丽人'
const defaultShareDesc = '内蒙古民族服饰领头羊！'
const defaultShareCover = 'https://mongoljingooapi.duuchin.com/profile/storage/1zd9yij0sf42xwss9kdf.png'
const defaultShareUrl = () => {
	if (isIOS) {
		return uni.getStorageSync('firstOpenLink')
	} else {
		return window.location.href.split('#')[0]
	}
}

const isWeiXinBrowser = isWeiXin()

export default class WxSdkUtil {
	#url; // 页面路径（分享或签名用）
	#tiecketInfo; // 权限验证参数
	#readyFlag = false; // 是否已初始化
	
	/**
	 * 初始化（外部调用）
	 */
	async init(url, options = {}) {
		if (!isWeiXinBrowser) {
			console.log('WxSdkUtil：请在微信浏览器中打开')
			return
		}
		this.#url = url || defaultShareUrl()
		console.log(222, this.#url)
		await this.#getTicketConfig()
		this.#wxConfig(options)
	}
	
	/**
	 * 是否已初始化
	 */
	get isReady() {
		return this.#readyFlag
	}
	
	/**
	 * 获取微信SDK
	 */
	get wx() {
		return $wx
	}
	
	/**
	 * 获取接口权限验证配置
	 */
	async #getTicketConfig() {
		const { data } = await wxTicketConfig({ url: this.#url })
		this.#tiecketInfo = data
	}
	
	/**
	 * 初始化接口权限验证配置
	 */
	#wxConfig({
		jsApiList = ['updateAppMessageShareData', 'updateTimelineShareData', 'showMenuItems', 'hideMenuItems'],
		hideShare = false,
		shareInfo = {}
	}) {
		$wx.config({
			debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来
			appId: this.#tiecketInfo.appId, // 必填，公众号的唯一标识
			timestamp: this.#tiecketInfo.timestamp, // 必填，生成签名的时间戳
			nonceStr: this.#tiecketInfo.nonceStr, // 必填，生成签名的随机串
			signature: this.#tiecketInfo.signature,// 必填，签名
			jsApiList, // 必填，需要使用的JS接口列表
		})
		$wx.ready(() => {
			this.#readyFlag = true
			if (!hideShare) {
				const shareData = {
					title: shareInfo.title || defaultShareTitle, // 分享标题
					desc: shareInfo.desc ?? defaultShareDesc, // 分享描述
					imgUrl: shareInfo.imgUrl || defaultShareCover, // 分享图标
					link: this.#url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				}
				$wx.updateAppMessageShareData({ 
					...shareData,
					success: function () {
						console.log('updateAppMessageShareData 配置成功')
					}
				})
				$wx.updateTimelineShareData({
					...shareData,
					success: function () {
						console.log('updateTimelineShareData 配置成功')
					}
				})
				$wx.showMenuItems({
				  menuList: [
						'menuItem:share:appMessage',
						'menuItem:share:timeline',
						'menuItem:share:qq',
						'menuItem:share:QZone',
					]
				});
				$wx.hideMenuItems({
				  menuList: [
						'menuItem:share:weiboApp',
						'menuItem:copyUrl',
						'menuItem:originPage',
						'menuItem:openWithQQBrowser',
						'menuItem:openWithSafari'
					]
				});
			} else {
				// 隐藏所有菜单项
				$wx.hideMenuItems({
				  menuList: [
						'menuItem:share:appMessage', 
						'menuItem:share:timeline',
						'menuItem:share:qq',
						'menuItem:share:weiboApp',
						'menuItem:share:QZone',
						'menuItem:copyUrl',
						'menuItem:originPage',
						'menuItem:openWithQQBrowser',
						'menuItem:openWithSafari'
					]
				});
			}
		})
		$wx.error(err => {
			console.log('config失败', err)
		})
	}
	
}